<?php

class ActivityController extends Controller {

    public function filters() {
        return array(
            'accessControl', // perform access control for CRUD operations
        );
    }

    public function accessRules() {
        return array(
            array('allow', // allow admin user to perform 'admin' and 'delete' actions
                'actions' => array('index', 'detail','opration','closed','record','help','search'),
                'users' => array('*'),
            ),
            array('allow', // allow admin user to perform 'admin' and 'delete' actions
                'actions' => array('join', 'getActivityCode','track','retrack'),
                'users' => array('@'),
            ),
            array('deny', // deny all users
                'users' => array('*'),
            ),
        );
    }
    
    //驗證用戶是否通過了驗證
    protected function check($type=0){
        if (!Helper::userStatus(Yii::app()->user->id)) {
            header("Content-type:text/html;charset=utf-8");
            if($type==0){
                echo "<script>alert('您尚未完成驗證，還無法參與!');location.href='" . Yii::app()->createUrl('site/userInfo') . "';</script>";
            }else{
                echo "<script>alert('您尚未完成驗證，還無法參與!');parent.location.href='" . Yii::app()->createUrl('site/userInfo') . "';</script>";
            }
            exit;
        }
    }

    public function actionIndex() {
        $class = $_GET['class'];
        if (!in_array($class, array('人氣限定', '時間限定', '贊助限定'))) {
            $class = '人氣限定';
        }
        switch ($class) {
            case '人氣限定':
                $classArr['class'] = $class;
                $classArr['image'] = 'mainbutton1.png';
                break;
            case '時間限定':
                $classArr['class'] = $class;
                $classArr['image'] = 'mainbutton2.png';
                break;
            case '贊助限定':
                $classArr['class'] = $class;
                $classArr['image'] = 'mainbutton3.png';
                break;
            default:
                $classArr['class'] = $class;
                $classArr['image'] = 'mainbutton1.png';
                break;
        }
        $condition = new CDbCriteria();
        $condition->addCondition("t.class='$class'");
        $condition->with = 'prize';
        $condition->with = 'records';
        $condition->addInCondition('t.status', array(1, 2, 3, 5));
        $count = Activity::model()->count($condition);
        $condition->order = 't.hot desc,t.dateline desc';
        $pager = new CPagination($count);
        $pager->pageSize = 9;
        $pager->applyLimit($condition);
        $rowTable = Activity::model()->findAll($condition);
        unset($condition);
        $rowset = array_chunk($rowTable, 3);
        $this->render('index', array('rowset' => $rowset, 'pages' => $pager, 'classArr' => $classArr));
    }

    //ajax反饋活動,開始倒計時或者開獎倒計時
    public function actionOpration() {
        $serial = $_REQUEST['serial'];
        
        //開始
        $condition = new CDbCriteria();
        $condition->addCondition('status=1');
        $condition->addCondition("starttime<='" . date('Y-m-d H:i:s') . "'");
        $condition->addCondition("serial='". $serial ."'");
        $row = Activity::model()->find($condition);
        unset($condition);
        if($row){
            Helper::openActivity($row->activityid);            
        }
        
        //開獎
        $condition = new CDbCriteria();
        $condition->addCondition('status=5');
        $condition->addCondition("serial='". $serial ."'");
        $row = Activity::model()->find($condition);
        unset($condition);
        if($row && time() >= (strtotime($row->endtime)+$row->delaytime)){
            //更改狀態為已開獎
            $row->status=4;
            $row->save();
        }
        echo CJSON::encode(array('success' => true));
    }
    
    //活動詳情
    public function actionDetail($id){    	
        $row = Activity::model()->with(array('records'=>array('order'=>'records.dateline desc')))->findByPk((int)$id);
        if(!$row){
            $this->redirect(array('index'));
        }
        if(count($row->records)>=$row->people){
            //關閉活動
            Helper::closeActivity($row->activityid);
            if($row->class=='時間限定'){
                //時間限定的，程序生成中獎人，並且更新狀態為待開獎
                Helper::winPrize($row->activityid);
            }            
            $row = Activity::model()->with('records')->findByPk((int)$id);
        }
        if(Yii::app()->user->id){
            $user = User::model()->findByPk(Yii::app()->user->id);
            $condition = new CDbCriteria();
            $condition->addCondition('activityid='.$row->activityid);
            $condition->addCondition('uid='.$user->uid);
            $times = Record::model()->count($condition);
            unset($condition);        
        }     
		
        $description=mb_substr(strip_tags($row->prize->description),0,500,"utf-8");
        global $htmlHeader;
    	$htmlHeader="
<meta property='og:title' content='".$row->prize->prizename."'/>
<meta property='og:description' content='$description'/>
<meta property='og:image' content='http://".$_SERVER["HTTP_HOST"]."/".Yii::app()->params['prizePath']."/".$row->prize->pics[0]->path."'/>
    	";
    	$_SESSION['htmlHeader']=$htmlHeader;

        $this->render('detail', array(
            'row' => $row,
            'times' => $times,
        ));
    }
    
    //參加活動-獲得通關密語
    public function actionJoin($id){
        $this->check(1);
        $this->layout = 'pop';
        $user = User::model()->findByPk(Yii::app()->user->id);
        $row = Activity::model()->with('records')->findByPk((int)$id);
        header("Content-type:text/html;charset=utf-8");
        //參與人數大於了最大參與人數
        if(count($row->records)>=$row->people){            
            echo '<script>alert("活動人數已滿！");parent.location.href="'.$this->createUrl('index').'";</script>';
            exit;
        }
        //自己的參與次數大於了活動允許的單人最大參與次數
        $condition = new CDbCriteria();
        $condition->addCondition('activityid='.$row->activityid);
        $condition->addCondition('uid='.$user->uid);
        $times = Record::model()->count($condition);
        unset($condition);
        if($times>=$row->times){
            echo '<script>alert("您已經超過本活動的最大參加次數！");parent.location.href="'.$this->createUrl('index').'";</script>';
            exit;
        }
        //鴻運點數不足
        if($user->hongyun<$row->hongyun){
            echo '<script>alert("您的鴻運點數不足，不能參加本次活動！");parent.location.href="'.$this->createUrl('index').'";</script>';
            exit;
        }
        
        //參與時間間隔未到
        if(Helper::getNextTime($user->uid)>0){
//            echo '<script>alert("您還需要等待'.  date("H:i:s",Helper::getNextTime($user->uid)).'才能再次參與活動！");parent.location.href="'.$this->createUrl('detail',array('id'=>$row->activityid)).'";</script>';
            echo '<script>alert("您還需要等待 '. gmstrftime('%H:%M:%S',Helper::getNextTime($user->uid)) .' 才能再次參與活動！");parent.location.href="'.$this->createUrl('detail',array('id'=>$row->activityid)).'";</script>';
  
            exit;
        }
        
        //提交
        if (Yii::app()->request->isPostRequest) {
            if($_POST['code']==$row->code){
                $trans = Yii::app()->db->beginTransaction();
                try {
                    //添加抽獎記錄
                    $record = new Record();
                    $record->activityid = $row->activityid;
                    $record->uid = $user->uid;                    
                    if($row->class=='時間限定'){
                        //時間限定用1-10十個號碼
                        //生成總數組
                        $codeArr = array();
                        for($i=1;$i<=10;$i++){
                            $codeArr[] = $i;
                        }
                        //生成已報名數組
                        $doneArr = array();
                        if($row->records){
                            foreach($row->records as $doneRow){
                                $doneArr[] = $doneRow->code;
                            }
                        }
                        //生成差集
                        $intersection = array_diff($codeArr, $doneArr);                        
                        //數組打亂
                        shuffle($intersection);
                        $record->code = $intersection[0];                        
                    }else{
                        //其他限定都用0000-9999一萬個號碼
                        //生成總數組
                        $codeArr = array();
                        for($i=10000;$i<20000;$i++){
                            $codeArr[] = substr($i, 1,4);
                        }
                        //生成已報名數組
                        $doneArr = array();
                        if($row->records){
                            foreach($row->records as $doneRow){
                                $doneArr[] = $doneRow->code;
                            }
                        }
                        //生成差集
                        $intersection = array_diff($codeArr, $doneArr);                        
                        //數組打亂
                        shuffle($intersection);
                        $record->code = $intersection[0];
                    }
                    $record->save();
                    //扣用戶的鴻運點數并添加記錄
                    if($row->hongyun){
                        $user->hongyun = $user->hongyun-$row->hongyun;
                        $user->save();
                        
                        //保存coin flow記錄
                        $flow = new CoinFlow();
                        $flow->uid = $user->uid;
                        $flow->type = 2;
                        $flow->amount = $row->hongyun;
                        $flow->flow_type = 2;
                        $flow->description = '活動（' . $row->activityid . '）扣取用戶鴻運點數。';
                        $flow->save();
                    }
                    
                    $trans->commit();
                    $result = true;
                } catch (Exception $e) {
                    $trans->rollback();
                    $result = false;
                }
                if($result){
                    echo '<script>alert("參與成功，您的抽獎號碼為：'.$record->code.'");</script>';
                }else{
                    echo '<script>alert("提交失敗！");</script>';
                }
                echo '<script>parent.location.href="'.$this->createUrl('detail',array('id'=>$row->activityid)).'";</script>';
                exit;
            }else{
                echo '<script>alert("通關密語輸入錯誤！");</script>';
            }
        }
        
        $this->render('join', array(
            'row' => $row,
        ));
    }
    
    //獲取活動通關密語
    public function actionGetActivityCode(){
        $this->check();
        $serial = $_REQUEST['serial'];
        $condition = new CDbCriteria();
        $condition->addCondition('status=2');
        $condition->addCondition("starttime<='" . date('Y-m-d H:i:s') . "'");
        $condition->addCondition("serial='". $serial ."'");
        $row = Activity::model()->find($condition);
        unset($condition);
        if($row){
            echo CJSON::encode(array('success' => true, 'msg' => $row->code));
        }else{
            echo CJSON::encode(array('success' => false, 'msg' => '活動參數錯誤'));
        }
    }
    
    //已結束的活動
    public function actionClosed(){
        $condition = new CDbCriteria();
        $condition->with = 'prize';
        $condition->addCondition('t.status=4');
        $count = Activity::model()->count($condition);
        $condition->order = 't.hot desc,t.dateline desc';
        $pager = new CPagination($count);
        $pager->pageSize = 3;
        $pager->applyLimit($condition);
        $rowTable = Activity::model()->with(array('records'=>array('condition'=>'win=1')))->findAll($condition);
        unset($condition);
        $this->render('closed', array(
            'rowTable' => $rowTable,
            'pages' => $pager,
        ));
    }
    
    //活動明細記錄
    public function actionRecord($id,$win=0){
        $this->layout = 'pop';
        $condition = new CDbCriteria();
        $condition->with = array('activity');  
        if($win==1){
            $condition->addCondition('t.win=1');
            $condition->addCondition('activity.status=4');
        }        
        $condition->order = 't.dateline desc';
        $condition->addCondition('t.activityid='.(int)$id);
        $count = Record::model()->count($condition);
//        $condition->order = 't.win desc,t.dateline desc';
        $pager = new CPagination($count);
        $pager->pageSize = 15;
        $pager->applyLimit($condition);
        $rowTable = Record::model()->findAll($condition);
        unset($condition);
        
        $this->render('record', array(
            'rowTable' => $rowTable,
            'pages' => $pager,
        ));
    }
    
    //活動追蹤
    public function actionTrack($id){
        $this->check();
        //查找是否有過追蹤記錄
        header("Content-type:text/html;charset=utf-8");
        $activity = Activity::model()->findByPk((int)$id);
        if(!$activity){
            echo '<script>alert("參數錯誤");window.location.href="'.$this->createUrl('index').'";</script>';
            exit;
        }
        
        $condition = new CDbCriteria();
        $condition->addCondition('uid='.Yii::app()->user->id);
        $condition->addCondition('activityid='.$activity->activityid);
        $row = Track::model()->count($condition);
        unset($condition);
        if(!$row){
            $track = new Track();
            $track->activityid = $activity->activityid;
            $track->uid = Yii::app()->user->id;
            if($track->save()){
                $msg = '追蹤成功';
            }else{
                $msg = '追蹤成功';
            }
        }else{
            $msg = '您已經追蹤過此活動';
        }
        echo '<script>alert("'.$msg.'");window.location.href="'.$this->createUrl('detail',array('id'=>$activity->activityid)).'";</script>';
    }
    
     //活動追蹤
    public function actionRetrack($id){
        $this->check();
        //查找是否有過追蹤記錄
        header("Content-type:text/html;charset=utf-8");
        $activity = Activity::model()->findByPk((int)$id);
        if(!$activity){
            echo '<script>alert("參數錯誤");window.location.href="'.$this->createUrl('index').'";</script>';
            exit;
        }
        
        $condition = new CDbCriteria();
        $condition->addCondition('uid='.Yii::app()->user->id);
        $condition->addCondition('activityid='.$activity->activityid);
        $row = Track::model()->find($condition);
        unset($condition);
        if($row){
            $row->delete();
        }
        echo '<script>alert("取消成功！");window.location.href="'.Yii::app()->createUrl('site/track').'";</script>';
    }
    
    //幫助
    public function actionHelp(){
        $this->render('help');
    }
    
    public function actionSearch() {
        $condition = new CDbCriteria();
        
        $class = $_GET['search_class'];
        if (!in_array($class, array('人氣限定', '時間限定', '贊助限定'))) {
            $class = '';
        }        

        switch ($class) {
            case '人氣限定':
                $classArr['image'] = 'mainbutton1.png';
				$classArr['map'] = true;
                break;
            case '時間限定':
                $classArr['image'] = 'mainbutton2.png';
				$classArr['map'] = true;
                break;
            case '贊助限定':
                 $classArr['image'] = 'mainbutton3.png';
				 $classArr['map'] = true;
                break;
            default:
                $classArr['image'] = 'mainbutton6.png';
                break;
        }
        
        if($class){
            $condition->addCondition("t.class='$class'");
        }
        
        $key = $_GET['search_key'];
        if($key){
            $condition->addCondition("activityname like '%".$key."%'");
        }
        
        $condition->addCondition("status in(1,2)");

        $condition->with = 'prize';
        $condition->with = 'records';
        $count = Activity::model()->count($condition);
        $condition->order = 't.hot desc,t.dateline desc';
        $pager = new CPagination($count);
        $pager->pageSize = 9;
        $pager->applyLimit($condition);
        $rowTable = Activity::model()->findAll($condition);
        unset($condition);
        $rowset = array_chunk($rowTable, 3);
        $this->render('search', array('rowset' => $rowset, 'pages' => $pager ,'classArr' => $classArr));
    }

}